package org.fixies.spreadsheet.text.org;

import org.fixies.resource.ResourceLoader;
import org.fixies.spreadsheet.interpreter.BookContext;
import org.fixies.spreadsheet.interpreter.SheetContext;
import org.junit.Test;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.Queue;

import static org.fixies.utils.Validator.notNull;

public class OrgBookContext implements BookContext {

    private final Queue<String> resources_ = new LinkedList<String>();

    private SheetContext current;

    private ResourceLoader resourceLoader_;

    private final Class<?> testClass_;

    public OrgBookContext(Class<?> testClass) {
        notNull(testClass);
        testClass_ = testClass;
    }


    @Override
    public SheetContext next() {
        if (!hasNext()) {
            return null;
        }
        String resourceName = resources_.poll();
        InputStream in = resourceLoader_.loadResource(resourceName);
        current = new OrgSheetContext(resourceName, in);
        return current;
    }

    @Override
    public SheetContext current() {
        return current;
    }

    @Override
    public boolean hasNext() {
        return !resources_.isEmpty();
    }


    @Override
    public void load(String resourceName, ResourceLoader resourceLoader) {
        resourceLoader_ = resourceLoader;
        for (Method m : testClass_.getMethods()) {
            if (m.isAnnotationPresent(Test.class)) {
                resources_.offer(resourceName + "/" + m.getName() + ".org");
            }
        }
    }
}
